import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/exam_category.dart';
import 'package:kxy_flutter_app/view/my/exam_history/exam_history_list_view.dart';

class ExamHistoryView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ExamHistoryViewState();
  }
}

class ExamHistoryViewState extends State<ExamHistoryView> {
  List<ExamCategory> cateList;
  Future loadFuture;

  @override
  void initState() {
    loadFuture = loadExamCateList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text('考试记录')),
      body: FutureBuilder(
        future: loadFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    return ListView(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      children: ListTile.divideTiles(
        tiles: cateList.map((cate) {
          return cateItemWidget(cate);
        }),
        context: context,
        color: Colors.black12,
      ).toList(),
    );
  }

  Widget cateItemWidget(ExamCategory cate) {
    return ListTile(
      title: Text(cate.name),
      onTap: () {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (cxt) => ExamHistoryListView(cateId: cate.id),
          ),
        );
      },
    );
  }

  Future loadExamCateList() async {
    var res = await Http.instance.post('/exam-app/exam/cate/list');
    if (res.code == 200) {
      setState(() {
        cateList = (res.data as List).where((item) => item['type'] == 1).map((item) {
          return ExamCategory.fromJson(item);
        }).toList();
      });
    }
  }
}
